package com.easyaccount.controller;

import com.easyaccount.bean.LoginUser;
import com.easyaccount.bean.MenuTree;
import com.easyaccount.bean.UserVO;
import com.easyaccount.commons.CommonResp;
import com.easyaccount.commons.TablePage;
import com.easyaccount.model.User;
import com.easyaccount.service.MenuService;
import com.easyaccount.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private MenuService menuService;

    @RequestMapping("login")
    @ResponseBody
    public CommonResp<LoginUser> login(LoginUser loginUser, HttpServletRequest request){
        HttpSession session = request.getSession();
        return userService.login(loginUser, session);
    }

    @RequestMapping("getInfo")
    @ResponseBody
    public CommonResp<LoginUser> getInfo(HttpServletRequest request){
        HttpSession session = request.getSession();
        LoginUser user = (LoginUser) session.getAttribute("user");
        if(user == null) return CommonResp.failed("获取用户信息失败",500);

        List<MenuTree> trees = menuService.toTree(menuService.getMenu(user.getId()));
        user.setMenus(trees);
        System.out.println(user);
        return CommonResp.success(user);
    }

    @RequestMapping("list")
    @ResponseBody
    public TablePage list(TablePage tablePage){
        return userService.list(tablePage,null);
    }

    @RequestMapping("search")
    @ResponseBody
    public TablePage search(TablePage tablePage, @RequestParam("searchValue") String searchValue){
        return userService.list(tablePage,searchValue);
    }

    @RequestMapping("add")
    @ResponseBody
    public CommonResp add(@RequestBody UserVO userVO){
        return userService.save(userVO);
    }

    @RequestMapping("update")
    @ResponseBody
    public CommonResp update(@RequestBody UserVO userVO){
        return userService.updateUser(userVO);
    }

    @RequestMapping("resetPwd")
    @ResponseBody
    public CommonResp resetPwd(User user){
        User result = userService.getUserById(user.getId());
        if (result != null){
            String phone = result.getPhone();
            user.setPassword(phone.substring(5));
        }

        return userService.updateUserPwd(user);
    }

    @RequestMapping("delete")
    @ResponseBody
    public CommonResp delete(User user){
        return userService.delete(user);
    }
}
